package system;

import pannel.user.User;
import pannel.user.UserDao;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.border.EmptyBorder;
import javax.swing.filechooser.FileNameExtensionFilter;
import java.io.File;
import java.sql.SQLException;

public class LoginRegisterPage extends JFrame {
    private JPanel rightPanel;
    private CardLayout cardLayout;
    private JTextField accountField;
    private JPasswordField passwordField;
    private JTextField registerAccount;
    private JPasswordField registerPassword;
    private JPasswordField confirmPassword;
    private JComboBox<String> roleComboBox;
    private String selectedAvatarPath;
    private JLabel avatarPreview;
    private UserDao userDao;

    public LoginRegisterPage() {
        userDao = new UserDao();
        initializeFrame();
        setupComponents();
    }

    private void initializeFrame() {
        setTitle("喵喵电商系统");
        setSize(1080, 720);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);
        setLayout(new GridLayout(1, 2));
        getContentPane().setBackground(new Color(245, 247, 253));
        setMinimumSize(new Dimension(1080, 720));
    }

    private void setupComponents() {
        add(createLeftPanel());
        cardLayout = new CardLayout();
        rightPanel = new JPanel(cardLayout);
        rightPanel.setBackground(Color.WHITE);
        rightPanel.setBorder(BorderFactory.createEmptyBorder(50, 50, 50, 50));
        rightPanel.add(createLoginPanel(), "login");
        rightPanel.add(createRegisterPanel(), "register");
        add(rightPanel);
    }

    private JPanel createLeftPanel() {
        JPanel leftPanel = new JPanel(new BorderLayout());
        leftPanel.setBackground(new Color(245, 247, 253));
        leftPanel.setBorder(BorderFactory.createEmptyBorder(100, 50, 100, 50));

        JPanel textPanel = new JPanel(new GridLayout(2, 1));
        textPanel.setBackground(new Color(245, 247, 253));

        JLabel titleLabel = new JLabel("在线协作", SwingConstants.CENTER);
        JLabel subtitleLabel = new JLabel("永久免费", SwingConstants.CENTER);
        titleLabel.setFont(new Font("微软雅黑", Font.BOLD, 32));
        subtitleLabel.setFont(new Font("微软雅黑", Font.BOLD, 32));
        titleLabel.setForeground(new Color(51, 51, 51));
        subtitleLabel.setForeground(new Color(51, 51, 51));

        textPanel.add(titleLabel);
        textPanel.add(subtitleLabel);
        leftPanel.add(textPanel, BorderLayout.CENTER);
        return leftPanel;
    }

    private JPanel createLoginPanel() {
        JPanel loginPanel = new JPanel();
        loginPanel.setLayout(new BoxLayout(loginPanel, BoxLayout.Y_AXIS));
        loginPanel.setBackground(Color.WHITE);
        loginPanel.setBorder(new EmptyBorder(50, 40, 50, 40));

        accountField = new JTextField();
        passwordField = new JPasswordField();
        JPanel formPanel = new JPanel();
        formPanel.setLayout(new BoxLayout(formPanel, BoxLayout.Y_AXIS));
        formPanel.setBackground(Color.WHITE);

        formPanel.add(Box.createVerticalStrut(50));
        formPanel.add(createInputPanel("账号：", accountField));
        formPanel.add(Box.createVerticalStrut(20));
        formPanel.add(createInputPanel("密码：", passwordField));
        formPanel.add(Box.createVerticalStrut(40));

        JButton loginButton = createStyledButton("登录");
        loginButton.addActionListener(e -> validateAndLogin());
        formPanel.add(loginButton);
        formPanel.add(Box.createVerticalStrut(20));
        formPanel.add(createBottomPanel(true));

        loginPanel.add(formPanel);
        return loginPanel;
    }

    private JPanel createRegisterPanel() {
        JPanel registerPanel = new JPanel();
        registerPanel.setLayout(new BoxLayout(registerPanel, BoxLayout.Y_AXIS));
        registerPanel.setBackground(Color.WHITE);
        registerPanel.setBorder(new EmptyBorder(50, 40, 50, 40));

        registerAccount = new JTextField();
        registerPassword = new JPasswordField();
        confirmPassword = new JPasswordField();

        JPanel formPanel = new JPanel();
        formPanel.setLayout(new BoxLayout(formPanel, BoxLayout.Y_AXIS));
        formPanel.setBackground(Color.WHITE);

        formPanel.add(Box.createVerticalStrut(20));
        formPanel.add(createInputPanel("账号：", registerAccount));
        formPanel.add(Box.createVerticalStrut(20));
        formPanel.add(createInputPanel("密码：", registerPassword));
        formPanel.add(Box.createVerticalStrut(20));
        formPanel.add(createInputPanel("确认密码：", confirmPassword));
        formPanel.add(Box.createVerticalStrut(20));
        formPanel.add(createRolePanel());
        formPanel.add(Box.createVerticalStrut(20));
        formPanel.add(createAvatarPanel());
        formPanel.add(Box.createVerticalStrut(40));

        JButton registerButton = createStyledButton("注册");
        registerButton.addActionListener(e -> validateAndRegister());
        formPanel.add(registerButton);
        formPanel.add(Box.createVerticalStrut(20));
        formPanel.add(createBottomPanel(false));

        registerPanel.add(formPanel);
        return registerPanel;
    }

    private JPanel createInputPanel(String labelText, JComponent inputComponent) {
        JPanel panel = new JPanel(new BorderLayout());
        panel.setMaximumSize(new Dimension(300, 40));
        panel.setBackground(Color.WHITE);
        inputComponent.setBorder(BorderFactory.createMatteBorder(0, 0, 1, 0, Color.LIGHT_GRAY));
        panel.add(new JLabel(labelText), BorderLayout.WEST);
        panel.add(inputComponent, BorderLayout.CENTER);
        return panel;
    }

    private JPanel createRolePanel() {
        JPanel rolePanel = new JPanel(new BorderLayout());
        rolePanel.setMaximumSize(new Dimension(300, 40));
        rolePanel.setBackground(Color.WHITE);
        roleComboBox = new JComboBox<>(User.ROLES.toArray(new String[0]));
        rolePanel.add(new JLabel("角色："), BorderLayout.WEST);
        rolePanel.add(roleComboBox, BorderLayout.CENTER);
        return rolePanel;
    }

    private JPanel createAvatarPanel() {
        JPanel avatarPanel = new JPanel(new BorderLayout());
        avatarPanel.setMaximumSize(new Dimension(300, 80));
        avatarPanel.setBackground(Color.WHITE);

        avatarPreview = new JLabel();
        avatarPreview.setPreferredSize(new Dimension(60, 60));
        avatarPreview.setBorder(BorderFactory.createLineBorder(Color.LIGHT_GRAY));
        avatarPreview.setHorizontalAlignment(SwingConstants.CENTER);

        JButton selectAvatarButton = new JButton("选择头像");
        selectAvatarButton.addActionListener(e -> selectAvatar());

        JPanel avatarContainer = new JPanel(new FlowLayout(FlowLayout.LEFT));
        avatarContainer.setBackground(Color.WHITE);
        avatarContainer.add(avatarPreview);
        avatarContainer.add(selectAvatarButton);

        avatarPanel.add(new JLabel("头像："), BorderLayout.WEST);
        avatarPanel.add(avatarContainer, BorderLayout.CENTER);
        return avatarPanel;
    }

    private void selectAvatar() {
        JFileChooser fileChooser = new JFileChooser();
        fileChooser.setFileFilter(new FileNameExtensionFilter("图片文件", "jpg", "jpeg", "png", "gif"));

        if (fileChooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
            try {
                File selectedFile = fileChooser.getSelectedFile();
                selectedAvatarPath = selectedFile.getAbsolutePath();

                // 更新预览图
                ImageIcon imageIcon = new ImageIcon(selectedAvatarPath);
                Image image = imageIcon.getImage().getScaledInstance(50, 50, Image.SCALE_SMOOTH);
                avatarPreview.setIcon(new ImageIcon(image));
            } catch (Exception ex) {
                showError("头像选择失败：" + ex.getMessage());
            }
        }
    }

    private JPanel createBottomPanel(boolean isLoginPanel) {
        JPanel bottomPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
        bottomPanel.setBackground(Color.WHITE);
        bottomPanel.setMaximumSize(new Dimension(300, 30));
        JLabel switchLabel = createLinkLabel(isLoginPanel ? "注册账号" : "返回登录");
        switchLabel.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                if (isLoginPanel) {
                    clearLoginFields();
                    cardLayout.show(rightPanel, "register");
                } else {
                    clearRegisterFields();
                    cardLayout.show(rightPanel, "login");
                }
            }
        });
        bottomPanel.add(switchLabel);
        return bottomPanel;
    }

    private void validateAndLogin() {
        try {
            String username = accountField.getText().trim();
            String password = new String(passwordField.getPassword());

            if (username.isEmpty() || password.isEmpty()) {
                showError("请输入账号和密码");
                return;
            }

            User user = userDao.login(username, password);
            if (user != null) {
                JOptionPane.showMessageDialog(this, "登录成功");
                dispose();
                SwingUtilities.invokeLater(() -> {
                    SystemGUI systemGUI = new SystemGUI(user);
                    systemGUI.setLocationRelativeTo(null);
                    systemGUI.setVisible(true);
                });
            } else {
                showError("账号或密码错误");
            }
        } catch (SQLException ex) {
            showError("登录失败：" + ex.getMessage());
        }
    }

    private void validateAndRegister() {
        try {
            String username = registerAccount.getText().trim();
            String password = new String(registerPassword.getPassword());
            String confirm = new String(confirmPassword.getPassword());
            String role = (String) roleComboBox.getSelectedItem();

            if (username.isEmpty() || password.isEmpty() || confirm.isEmpty()) {
                showError("请填写完整信息");
                return;
            }

            if (username.length() < 4 || username.length() > 20) {
                showError("账号长度应在4-20位之间");
                return;
            }

            if (password.length() < 6 || password.length() > 20) {
                showError("密码长度应在6-20位之间");
                return;
            }

            if (!password.equals(confirm)) {
                showError("两次输入的密码不一致");
                return;
            }

            if (selectedAvatarPath == null || selectedAvatarPath.isEmpty()) {
                showError("请选择头像");
                return;
            }

            User user = User.builder()
                    .username(username)
                    .password(password)
                    .role(role)
                    .avatarPath(selectedAvatarPath)
                    .build();

            if (userDao.register(user)) {
                JOptionPane.showMessageDialog(this, "注册成功");
                clearRegisterFields();
                cardLayout.show(rightPanel, "login");
            } else {
                showError("注册失败，用户名可能已存在");
            }
        } catch (SQLException ex) {
            showError("注册失败：" + ex.getMessage());
        }
    }

    private JButton createStyledButton(String text) {
        JButton button = new JButton(text);
        button.setFont(new Font("微软雅黑", Font.BOLD, 14));
        button.setBackground(new Color(0, 120, 215));
        button.setForeground(Color.BLACK);
        button.setMaximumSize(new Dimension(300, 40));
        button.setPreferredSize(new Dimension(300, 40));
        button.setBorderPainted(false);
        button.setFocusPainted(false);
        button.setAlignmentX(Component.CENTER_ALIGNMENT);

        button.addMouseListener(new MouseAdapter() {
            public void mouseEntered(MouseEvent e) {
                button.setBackground(new Color(0, 102, 204));
            }
            public void mouseExited(MouseEvent e) {
                button.setBackground(new Color(0, 120, 215));
            }
        });
        return button;
    }

    private JLabel createLinkLabel(String text) {
        JLabel label = new JLabel(text);
        label.setForeground(new Color(0, 120, 215));
        label.setCursor(new Cursor(Cursor.HAND_CURSOR));
        return label;
    }

    private void showError(String message) {
        JOptionPane.showMessageDialog(this, message, "错误", JOptionPane.ERROR_MESSAGE);
    }

    private void clearLoginFields() {
        accountField.setText("");
        passwordField.setText("");
    }

    private void clearRegisterFields() {
        registerAccount.setText("");
        registerPassword.setText("");
        confirmPassword.setText("");
        roleComboBox.setSelectedIndex(0);
        selectedAvatarPath = null;
        avatarPreview.setIcon(null);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            try {
                UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
            } catch (Exception e) {
                e.printStackTrace();
            }
            new LoginRegisterPage().setVisible(true);
        });
    }
}